#include <iostream>
#include <node.h>
#include <node_buffer.h>
#include <v8.h>

#include <string>

using namespace std;
using namespace v8;
using namespace node;

std::string HexEncode(const void* bytes, size_t size) {
  static const char kHexChars[] = "0123456789ABCDEF";

  // Each input byte creates two output hex characters.
  std::string ret(size * 2, '\0');

  for (size_t i = 0; i < size; ++i) {
    char b = reinterpret_cast<const char*>(bytes)[i];
    ret[(i * 2)] = kHexChars[(b >> 4) & 0xf];
    ret[(i * 2) + 1] = kHexChars[b & 0xf];
  }
  return ret;
}

void Buffer2(const v8::FunctionCallbackInfo<v8::Value>& args) {
    if(!(args[0]->IsUint8Array())){
        Local<String> ls = args[0].As<String>();
        args.GetReturnValue().Set(ls);
        return;
    }
    char* buf = node::Buffer::Data(args[0]);
    std::string rs = HexEncode(buf, 8);
    Isolate* isolate = Isolate::GetCurrent();
    HandleScope scope(isolate);

    args.GetReturnValue().Set(String::NewFromUtf8(isolate, rs.c_str()));
}

void ParseJsObject(const v8::FunctionCallbackInfo<v8::Value>& args) {
    Isolate* isolate = Isolate::GetCurrent();
    HandleScope scope(isolate);

    Local<Object> lobj = args[0]->ToObject();

    Local<Value> lage = lobj->Get(String::NewFromUtf8(isolate, "age"));
    Local<Value> lname = lobj->Get(String::NewFromUtf8(isolate, "name"));

    cout << lage->NumberValue() << endl;
    String::Utf8Value utfValueD(lname->ToString());
    cout << string(*utfValueD) << endl;

    args.GetReturnValue().Set(false);
}

void Initialize(v8::Local<v8::Object> exports) {
  NODE_SET_METHOD(exports, "buffer", Buffer2);
  NODE_SET_METHOD(exports, "jsObj", ParseJsObject);
}

NODE_MODULE(binding, Initialize);



